package repository

import (
	"gorm.io/gorm/clause"
	"niu-video/app/model"
	"niu-video/pkg/db"
)

var LikeRepository = newLikeRepository()

func newLikeRepository() *likeRepository {
	return &likeRepository{}
}

type likeRepository struct {
	baseRepository
}

// 获取用户like
func (u *likeRepository) GetUserLike(videoId int64, userId int64) (like model.Like) {
	db.DB.Where("video_id = ?", videoId).Where("user_id = ?", userId).First(&like)
	return
}

func (u *likeRepository) Create(video *model.Like) (err error) {
	err = db.DB.Create(video).Error
	return err
}

func (u *likeRepository) Delete(videoId int64, userId int64) (err error) {
	db.DB.Where("video_id = ?", videoId).Where("user_id = ?", userId).Delete(&model.Like{})
	return err
}

// LikeCountByUserId
//
//	@Description: 获取一个用户的点赞数量
//	@receiver v
//	@param videoId
//	@return count
func (l *likeRepository) LikeCountByUserId(userId int64) (count int64) {
	db.DB.Model(&model.Like{}).
		Joins("left join video on video.video_id = like.video_id").
		Where("like.user_id = ?", userId).
		Where("is_delete", false).
		Count(&count)
	return
}

// LikeUserVideo
//
//	@Description: 获取用户点赞记录的列表分页
//	@receiver l
//	@param userId
//	@return videos
func (l *likeRepository) LikeUserVideo(page int, pageSize int, userId int64) (videos []model.Video, err error) {
	if err = db.DB.Debug().Table("like").
		Select("video.*").
		Joins("left join video on video.video_id = like.video_id").
		Where("like.user_id = ?", userId).
		Order(clause.OrderByColumn{
			Column: clause.Column{
				Name: "create_time",
			},
			Desc: true,
		}).
		Offset((page-1)*pageSize).
		Limit(pageSize).
		Where("is_delete", false).
		Find(&videos).Error; err != nil {
		return videos, err
	}
	return
}
